package com.devbobcorn.nekoration.client.rendering;

import com.devbobcorn.nekoration.client.rendering.chunks.ChunkModelRender;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.RegionRenderCacheBuilder;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.vector.Vector3d;

public class ChunkModel {
    private static final Logger LOGGER = LogManager.getLogger("Chunk Model");

    public final ChunkModelRender chunkRender;
    private boolean isCompiled = false;
    private boolean error = false;

    private ChunkModel(final ChunkModelRender chunkRender, final RegionRenderCacheBuilder regionRenderCacheBuilder) {
        this.chunkRender = chunkRender;
    }

    @SuppressWarnings("resource")
    public static ChunkModel forTileEntity(final TileEntity tileEntity) {
        final ChunkModelRender chunkRender = new ChunkModelRender(tileEntity.getLevel(), Minecraft.getInstance().levelRenderer);
        final BlockPos pos = tileEntity.getBlockPos();

        chunkRender.setOrigin((pos.getX() >> 4) << 4, (pos.getY() >> 4) << 4, (pos.getZ() >> 4) << 4);

        return new ChunkModel(chunkRender, new RegionRenderCacheBuilder());
    }

    @SuppressWarnings("resource")
    public void compile() {
        if (error) return;
        try {
            final ChunkModelRender modelRender = this.chunkRender;
            final Vector3d pos = Minecraft.getInstance().gameRenderer.getMainCamera().getPosition();
            modelRender.setCamera(pos);
            modelRender.compileModel();
            LOGGER.info("Model " + (error ? "failed to compile." : "compiled successfully."));

            this.isCompiled = true;
        } catch (Exception e) {
            error = true;
            e.printStackTrace();
        }
    }

    public boolean isCompiled() {
        return isCompiled;
    }

    public boolean getError() {
        return error;
    }
}